#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <search.h>

#define DEBUG_LOG(fmt, ...) sprintf(stdout, fmt, __VA_ARGS__)

// static void *root = NULL;

int compare(const void *pa, const void *pb)
{
    return strcmp((const char *)pa, (const char *)pb);
}

void action(const void *nodep, const VISIT which, const int depth)
{
    int *datap;

    switch (which) {
        case preorder:
            break;
        case postorder:
            datap = *(int **) nodep;
            printf("%6d\n", *datap);
            break;
        case endorder:
            break;
        case leaf:
            datap = *(int **) nodep;
            printf("%6d\n", *datap);
            break;
    }
}
typedef struct __mobile_node__
{
    char mobile[16];
}Mobile;

int duplication(char *sample, Mobile **mobile, int *count)
{
    int i = 0, j = 0, num = 0;
    void *val, *root = NULL, *pfind = NULL;
    char *strTempPtr = NULL, *saveptr = NULL;

    *mobile = (Mobile *)malloc(sizeof(Mobile));

    strTempPtr = strtok_r(sample, ",", &saveptr);
    while (strTempPtr)
    {
        Mobile *temp = NULL;
        temp = malloc(sizeof(Mobile));
        pfind = (void *)temp->mobile;
        strncpy(temp->mobile, strTempPtr, sizeof(Mobile));

        val = tsearch(pfind, &root, compare);
        if (*(char **)val == (char *)pfind)
        {
            // 说明二叉树中没有此节点，那么保存到自定义数据结构中
            *mobile = (Mobile *)realloc(*mobile, sizeof(Mobile)*(i+1));

            strncpy((*mobile)[i].mobile, strTempPtr, sizeof(Mobile));

            ++i; ++num;
        }
        strTempPtr = strtok_r(NULL, ",", &saveptr);
    }
    *count = num;

    printf("i:%d, num:%d\n", i, num);
    for (j = 0; j < num; ++j)
        printf("num:%d, mobile:%s\n", j, (*mobile)[j].mobile);

    tdestroy(root, free);
    return 0;
}

int main(int argc, char *argv[])
{
    Mobile *mobile = NULL;
    int num = 0;
    char sample[] = 
        "18010495368,18010495369,18010495367,"
        "18010495367,18010495366,18010495369";

    duplication(sample, &mobile, &num);

    free(mobile);

    return 0;
}

